package xyz.second.ask_for_leave_manage_module.serivce.impl;

import org.springframework.stereotype.Service;
import xyz.second.ask_for_leave_manage_module.mapper.AskForLeaveRecordMapper;
import xyz.second.ask_for_leave_manage_module.serivce.AskForLeaveManageService;
import xyz.second.ask_for_leave_manage_module.mapper.result.AskForLeaveRecordResult;
import xyz.second.common.exception.NotImplementedException;
import xyz.second.database.entity.AskForLeave;
import xyz.second.database.mapper.AskForLeaveMapper;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AskForLeaveManageServiceImpl implements AskForLeaveManageService {

    private final AskForLeaveRecordMapper askForLeaveRecordMapper;
    private final AskForLeaveMapper askForLeaveMapper;

    public AskForLeaveManageServiceImpl(
        AskForLeaveRecordMapper askForLeaveRecordMapper,
        AskForLeaveMapper askForLeaveMapper
    ) {
        this.askForLeaveRecordMapper = askForLeaveRecordMapper;
        this.askForLeaveMapper = askForLeaveMapper;
    }

    @Override
    public List<AskForLeaveRecordData> getAllAskForLeaveRecord() {
        return askForLeaveRecordMapper.selectAllRecord().stream().map(this::resultToData)
                .collect(Collectors.toList());
    }

    @Override
    public List<AskForLeaveRecordData> getStudentAskForLeaveRecord(String studentAccount) {
        return askForLeaveRecordMapper.selectRecordByAskAccount(studentAccount)
                .stream().map(this::resultToData)
                .collect(Collectors.toList());
    }

    @Override
    public void askForLeave(String studentAccount, String reason) {
        AskForLeave newAsk = AskForLeave.builder()
                .askAccount(studentAccount)
                .askStatus(AskState.WAIT.ordinal())
                .askTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")))
                .askReason(reason).build();
        askForLeaveMapper.insert(newAsk);
    }

    @Override
    public void receiveAsk(int askId, String studentAccount, String handlerAccount) {
        // TODO("更新对应askId的请假记录状态为1，且处理人为handlerAccount")
        throw new NotImplementedException();
    }

    @Override
    public void rejectAsk(int askId, String studentAccount, String handlerAccount, String reason) {
        // TODO("更新对应askId的请假记录状态为2，且处理人为handlerAccount，不通过理由为reason")
        throw new NotImplementedException();
    }

    private AskForLeaveRecordData resultToData(AskForLeaveRecordResult record) {
        return new AskForLeaveRecordData(
                record.getId(), record.getAskAccount(), record.getAskUsername(), record.getAskStatus(),
                record.getAskTime(), record.getHandlerAccount(), record.getHandlerUsername(),
                record.getRejectReason(), record.getHandleTime(), record.getAskReason()
        );
    }
}
